<template>
	<scroll-view class="categoryLevelOne" :scroll-left="scrollLeft" scroll-with-animation :show-scrollbar="false" scroll-x>
		<!-- 选项 -->
		<view class="categoryLevelOne-scroll">
			<view
				class="categoryLevelOneItem"
				:class="{ active: selectedItem.name === item.name }"
				@click="selectCategoryOne(item, index)"
				v-for="(item, index) in categoryList"
				:key="index"
			>
				<image :src="item.icon" mode="aspectFit"></image>
				<text>{{ item.name }}</text>
			</view>
		</view>
	</scroll-view>
</template>

<script>
export default {
	name: 'JCategoryLevelOne',
	props: {
		// 分类列表数据
		categoryList: {
			type: Array,
			default: () => []
		},
		// 当前选中的分类项
		selectedItem: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			scrollLeft: 0
		};
	},
	methods: {
		// 选择一级分类
		selectCategoryOne(item, index) {
			console.log('选择一级分类:', item);

			// 计算滚动位置，使选中的分类居中显示
			this.calculateScrollPosition(item, index);

			// 向父组件发送事件
			this.$emit('category-change', item, index);
		},

		// 计算滚动位置，使选中的分类居中显示
		calculateScrollPosition(item, currentIndex) {
			// 获取当前分类在列表中的索引
			if (currentIndex === -1) return;

			// 确保DOM已更新
			this.$nextTick(() => {
				// 使用uni.createSelectorQuery()获取实际DOM元素信息
				const query = uni.createSelectorQuery().in(this);

				// 获取scroll-view的宽度
				query.select('.categoryLevelOne').boundingClientRect();

				// 获取所有分类项的宽度信息
				query.selectAll('.categoryLevelOneItem').boundingClientRect();

				// 执行查询
				query.exec((res) => {
					const scrollRect = res[0];
					const itemRects = res[1];

					if (!scrollRect || !itemRects || itemRects.length === 0) return;

					// 计算选中项之前所有项的累计宽度
					let scrollLeft = 0;
					for (let i = 0; i < currentIndex; i++) {
						scrollLeft += itemRects[i].width;
					}

					// 获取选中项的宽度
					const selectedItemWidth = itemRects[currentIndex].width;

					// 计算滚动位置，使选中项居中
					// 滚动位置 = 选中项之前所有项的总宽度 - (scroll-view宽度 - 选中项宽度) / 2
					const centerScrollLeft = scrollLeft - (scrollRect.width - selectedItemWidth) / 2;

					// 确保滚动位置不为负数
					this.scrollLeft = Math.max(0, centerScrollLeft);
				});
			});
		}
	}
};
</script>

<style lang="less" scoped>
@categoryLevelOneHeight: 160rpx;
@basecolor: #246ef9;

.categoryLevelOne {
	display: flex;
	align-items: center;
	height: @categoryLevelOneHeight;
	background: #f3f4f6;

	.categoryLevelOne-scroll {
		display: flex;
		height: 100%;

		.categoryLevelOneItem.active {
			background: rgba(36, 110, 249, 0.05);
			color: @basecolor;
			font-weight: 600;
		}

		.categoryLevelOneItem {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100%;
			// width: fit-content;
			min-width: @categoryLevelOneHeight;
			padding: 10rpx 10rpx;
			color: #333;
			line-height: 1.2;
			font-size: 26rpx;
			font-weight: 400;
			image {
				flex-shrink: 0;
				height: 100rpx;
				width: 100rpx;
			}

			text {
			}
		}
	}
}
</style>






